package com.tma.demo;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class BadActivity extends Activity implements OnClickListener {
    private static final String TAG = "BadActivity";
    private TextView mTaskProgressTextView;
    private Button mDoLongTaskButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bad);

        mTaskProgressTextView = (TextView) findViewById(R.id.tv_task_progress);
        mDoLongTaskButton = (Button) findViewById(R.id.btn_do_long_task);
        mDoLongTaskButton.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_bad, menu);
        return true;
    }

    public void onClick(View v) {
        handleButtonClicked();
    }

    /**
     * We are holding the main thread. If our task takes more than 5 seconds to
     * complete, Android will throw ANR (Application Not Responding) message.
     */
    private void handleButtonClicked() {
        // THIS IS A BAD PRACTISE!!!
        // THE MAIN THREAD MUST NOT BE HOLD UP BY LONG TASK
        // 
        // SOLUTION:
        // The long task must be handled by additional thread or using AsynTask
        for (int i = 0; i < 5; i++) {
            sleep(1000);
            doWork(i + 1);
        }
    }

    private void doWork(int percent) {
        String s = getString(R.string.tv_task_progress) + ": " + percent + "/5";
        // NOTE THAT: Because the main thread is still busy to process button's clicked event
        // We may not see the updated status on UI
        mTaskProgressTextView.setText(s);
    }

    private void sleep(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }
}
